<?php

include 'lib.php';


ini_set('display_errors', 1);
$posts = Database::find("posts", array("embeds_scraped" => '0'), null, "RAND()", 50);

$download = $_GET['download'];
var_dump($posts);

foreach ($posts as $post)
{
    scrapeEmbeds($post, $download);
}

function scrapeEmbeds($post, $download)
{
    Database::save("posts", array("id" => $post['id'], 'embeds_scraped' => '1'));
    
    $html_text = file_get_contents($post['link']);

    $html = new DomDocument();
    $html->preserveWhiteSpace = false;
    
    $html->loadXML($html_text);
    $html->loadHTML($html_text);
    $xpath = new DomXPath($html);    
    
    $objects = $html->getElementsByTagName('object');
    
    foreach ($objects as $object)
    {
        $src = $object->getAttribute('data');
        if (!$src) $src = $object->getElementsByTagName('embed')->item(0)->getAttribute("src");
        $exists = Database::find("embeds", array("src" => $src));
        
        if (!$exists)
        {            
        
             if (strpos($src, "youtube.com"))
            {
                $type = "youtube";
            }
            else if (strpos($src, "myspace"))
            {
                $type = "myspace";
            }
            else if (strpos($src, "mtvnservices"))
            {
                $type = "mtvnservices";
            }
            else if (strpos($src, "vimeo"))
            {
                $type = "vimeo";
            }
            else if (strpos($src, "dailymotion"))
            {
                $type = "dailymotion";
            }
            else if (strpos($src, "soundcloud"))
            {
                $type = "soundcloud";
            }
            else $type = "unknown";            
                $embed_id = Database::save("embeds", array(
                    'src' => $src,
                    'post_id' => $post['id'],
                    'type' => $type
                ));
                
                var_dump($embed_id);
                
               

            
        }
    }
}

?>